<?php
namespace modules\iChat\libs;

class FS
{
	//写入
	public static function write($info, $path)
	{
		$info = is_array($info) ? json_encode($info) : $info;
		file_put_contents($path, $info . PHP_EOL, FILE_APPEND);
	}
	//正向查找
	public static function search($tag, $file)
	{
		if (file_exists($file)) {
			$fp = fopen($file, 'r');
			while ($line = fgets($fp, 4096)) {
				$pos   = strpos($line, ':');
				$first = substr($line, 0, $pos);
				if ($first == $tag) {
					return json_decode(substr($line, $pos+1), true);
				}
			}
			fclose($fp);	
		}
		return false;
	}
	//查找多个
	//$limit =0;则全部找出
	public static function searchMulti($tag, $file, $limit = 0)
	{
		if (file_exists($file)) {
			$cursor   = 0;
			$resource = [];
			$fp = fopen($file, 'r');
			while ($line = fgets($fp, 4096)) {
				$pos   = strpos($line, ':');
				$first = substr($line, 0, $pos);
				if ($first == $tag) {
					++$cursor;
					if ($limit && $cursor > $limit) break;
					$resource[] = json_decode(substr($line, $pos+1), true);
				}
			}
			fclose($fp);
			return $resource;
		}
		return false;
	}
	//写入
	//$atEnd 是否写在文件尾部
	public static function puts($tag, Array $data, $file, $atEnd = true)
	{
		$info = $tag . ':' . json_encode($data);
		//file_put_contents($file, $info . PHP_EOL, FILE_APPEND);
		$fp = fopen($file, 'a');
		flock($fp, LOCK_EX);
		if ($atEnd) {
			fseek($fp, 0, SEEK_END);
		} else {
			fseek($fp, 0, SEEK_SET);
		}
		fwrite($fp, $info . PHP_EOL);
		flock($fp, LOCK_UN);
		fclose($fp);

	}
	//删除
	public static function delete($tag, $file)
	{
		$tempFile  = $file . '.temp';
		$tempfp    = fopen($tempFile, 'w');
		flock($tempfp, LOCK_EX);
		$fp        = fopen($file, 'r');
		$flag      = false;
		while ($line = fgets($fp, 4096)) {
			$pos   = strpos($line, ':');
			$first = substr($line, 0, $pos);
			if ($first == $tag) {
				$flag = true;
				continue;
			}
			fwrite($tempfp, $line);
		}
		flock($tempfp, LOCK_UN);
		fclose($fp);
		fclose($tempfp);
		if ($flag) {
			unlink($file);
			rename($tempFile, $file);
			return true;
		} else {
			unlink($tempFile);
			return false;
		}
	}
}